<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <h2><span><b>线下预约登记</b></span></h2>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="待安排" name="pending"></el-tab-pane>
          <el-tab-pane label="已安排" name="arranged"></el-tab-pane>
        </el-tabs>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form class="search-form" v-if="['pending', 'arranged'].includes(activeTab)">
      <el-form-item>
        <el-input
            v-model="searchKey"
            placeholder="请输入学生姓名/账号/学号/联系电话关键词查询"
            style="width: 400px;"
        >
          <template #append>
            <el-button type="primary" @click="getList(activeTab)">查询</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <!-- 预约列表 -->
    <el-table
        :data="activeTab === 'pending' ? tableData : arrangedTableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <template v-if="activeTab === 'pending'">
        <!-- 新增多选框列 -->
        <el-table-column type="selection" width="30"></el-table-column>
      </template>
      <el-table-column label="序号" width="60">
        <template #default="{ row }">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column label="学生姓名" prop="studentName"></el-table-column>
      <el-table-column label="账号/学号" prop="studentId"></el-table-column>
      <el-table-column label="心理量表1" prop="scale1"></el-table-column>
      <el-table-column label="心理量表2" prop="scale2"></el-table-column>
      <el-table-column label="学院" prop="college"></el-table-column>
      <el-table-column label="责任辅导员" prop="counselor"></el-table-column>
      <el-table-column label="联系电话" prop="phone" width="120"></el-table-column>
      <el-table-column label="预约渠道" prop="channel"></el-table-column>
      <el-table-column label="咨询状态" prop="status">
        <template #default="{ row }">
          <el-tag :type="row.status === '挂起' ? 'warning' : 'success'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
              type="primary"
              plain
              size="small"
              :disabled="activeTab === 'arranged'"
              :text="activeTab === 'pending' ? '安排评估' : '已安排'"
              @click="showAssessmentDialog(row)"
          >
            {{ activeTab === 'pending' ? '安排评估' : '已安排' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部信息 -->
    <div class="bottom-info" v-if="['pending', 'arranged'].includes(activeTab)">
      <template v-if="activeTab === 'pending'">
        <el-button type="primary" @click="handleBatchImport">批量录入结果</el-button>
      </template>
      <!-- 分页条 -->
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSizeVal"
          :page-sizes="[4, 8, 12]"
          layout="jumper, total, sizes, prev, pager, next"
          background
          :total="activeTab === 'pending' ? totalCount : arrangedTotalCount"
          @size-change="(val) => handleSizeChange(val, activeTab)"
          @current-change="(val) => handleCurrentChange(val, activeTab)"
      />
    </div>

    <!-- 安排评估弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form ref="assessmentFormRef" :model="assessmentForm" :rules="assessmentRules">
        <!-- 评估优先级 -->
        <el-form-item label="评估优先级" prop="priority">
          <el-radio-group v-model="assessmentForm.priority">
            <el-radio-button label="immediate">即刻评估</el-radio-button>
            <el-radio-button label="soon">尽快评估</el-radio-button>
            <el-radio-button label="none">暂不用评估</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 根据评估优先级显示不同内容 -->
        <template v-if="assessmentForm.priority !== 'none'">
          <el-form-item label="可预约咨询师" prop="counselorId">
            <el-select v-model="assessmentForm.counselorId" placeholder="请选择咨询师">
              <el-option
                  v-for="counselor in counselors"
                  :key="counselor.id"
                  :label="`${counselor.name} (${counselor.phone})`"
                  :value="counselor.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="可咨询时间" prop="appointmentTime">
            <el-date-picker
                v-model="assessmentForm.appointmentTime"
                type="datetime"
                placeholder="请选择日期和时间"
                size="default"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="assessmentForm.priority === 'none'"
            />
          </el-form-item>

          <el-form-item label="咨询地点" prop="location">
            <el-input
                v-model="assessmentForm.location"
                placeholder="请输入咨询地点,详细到门牌号"
            />
          </el-form-item>
        </template>

        <!-- 暂不用评估提示 -->
        <template v-if="assessmentForm.priority === 'none'">
          <el-divider />
          <el-alert
              type="info"
              title="温馨提示"
              :closable="false"
              class="tips"
          >
            暂不用评估的，就不需要安排评估了。
          </el-alert>
        </template>

        <!-- 温馨提示 -->
        <template v-if="assessmentForm.priority === 'immediate' || assessmentForm.priority === 'soon'">
          <el-divider />
          <el-alert
              type="info"
              title="温馨提示"
              :closable="false"
              class="tips"
          >
            <p>·{{assessmentForm.priority === 'immediate' ? '即刻评估' : '尽快评估'}}需要学生在移动端上"我的咨询"中操作确认咨询师和时间的安排</p>
            <p>·学生确认之后，再进入到"评估分诊"中进行等待</p>
          </el-alert>
        </template>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssessment">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { appointmentMockData } from "../../api/mockData/noappointment.ts";
import { rightAppointmentMockData } from "../../api/mockData/rightappointment.ts";
import { Calendar } from "@element-plus/icons-vue";

// 分页条数据模型
const pageNum = ref(1); // 当前页 - 待安排
const pageSize = ref(4); // 每页条数 - 待安排
const arrangedPageNum = ref(1); // 当前页 - 已安排
const arrangedPageSize = ref(4); // 每页条数 - 已安排
const tableData = ref([]);
const arrangedTableData = ref([]);
const searchKey = ref(""); // 搜索关键词

// 统计数据
const arrangedCount = ref(rightAppointmentMockData.length); // 已安排数量
let totalCount = ref(appointmentMockData.length); // 总数量 - 待安排
let arrangedTotalCount = ref(rightAppointmentMockData.length); // 总数量 - 已安排

// 用于存储选中的行数据
const selectedRows = ref<any[]>([]);

// 新增：批量录入结果按钮点击事件，弹出提示
const handleBatchImport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择需要批量录入结果的行");
    return;
  }
  showAssessmentDialog(selectedRows.value[0]);
};

// 弹窗相关数据
const dialogVisible = ref(false);
const dialogTitle = ref("安排评估");
const currentStudents = ref<any[]>([]);

// 咨询师数据（改为下拉框格式）
const counselors = ref([
  { id: 1, name: "咨询师姓名1", phone: "15888888888" },
  { id: 2, name: "咨询师姓名2", phone: "15888888888" },
]);

// 评估表单数据（添加counselorId和appointmentTime字段）
const assessmentForm = ref({
  priority: "immediate", // 评估优先级，默认即刻评估
  location: "", // 咨询地点
  counselorId: null, // 选择的咨询师ID
  appointmentTime: null // 预约时间（包含日期和时间）
});

// 评估表单验证规则
const assessmentRules = ref({
  priority: [{ required: true, message: '请选择评估优先级', trigger: 'change' }],
  location: [
    { required: true, message: '请输入咨询地点', trigger: 'blur' },
  ],
  counselorId: [
    { required: true, message: '请选择咨询师', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择咨询时间', trigger: 'change' }
  ]
});

const assessmentFormRef = ref(null);

// 计算属性：处理 current-page 绑定逻辑
const currentPage = computed({
  get() {
    return activeTab.value === 'pending' ? pageNum.value : arrangedPageNum.value;
  },
  set(val) {
    if (activeTab.value === 'pending') {
      pageNum.value = val;
    } else {
      arrangedPageNum.value = val;
    }
  }
});

// 计算属性：处理 page-size 绑定逻辑
const pageSizeVal = computed({
  get() {
    return activeTab.value === 'pending' ? pageSize.value : arrangedPageSize.value;
  },
  set(val) {
    if (activeTab.value === 'pending') {
      pageSize.value = val;
    } else {
      arrangedPageSize.value = val;
    }
  }
});

// 获取预约列表，结合搜索和分页逻辑
const getList = (tab: string) => {
  const dataSource = tab === 'pending' ? appointmentMockData : rightAppointmentMockData;
  const currentPageNum = tab === 'pending' ? pageNum.value : arrangedPageNum.value;
  const currentPageSize = tab === 'pending' ? pageSize.value : arrangedPageSize.value;
  // 模拟API请求延迟
  setTimeout(() => {
    let filteredData = dataSource;
    // 先根据搜索关键词过滤数据
    if (searchKey.value) {
      filteredData = filteredData.filter(item =>
          item.studentName.includes(searchKey.value) ||
          item.studentId.includes(searchKey.value) ||
          item.phone.includes(searchKey.value)
      );
    }
    // 更新总数量为过滤后的数据长度
    if (tab === 'pending') {
      totalCount.value = filteredData.length;
    } else {
      arrangedTotalCount.value = filteredData.length;
    }
    // 根据分页参数截取当前页数据
    const startIndex = (currentPageNum - 1) * currentPageSize;
    const endIndex = startIndex + currentPageSize;
    if (tab === 'pending') {
      tableData.value = filteredData.slice(startIndex, endIndex);
    } else {
      arrangedTableData.value = filteredData.slice(startIndex, endIndex);
    }
  }, 300);
};

// 当每页条数发生变化时调用
const handleSizeChange = (val: number, tab: string) => {
  if (tab === 'pending') {
    pageSize.value = val;
  } else {
    arrangedPageSize.value = val;
  }
  getList(tab);
};

// 当当前页面发生变化时调用
const handleCurrentChange = (val: number, tab: string) => {
  if (tab === 'pending') {
    pageNum.value = val;
  } else {
    arrangedPageNum.value = val;
  }
  getList(tab);
};

// 显示安排评估弹窗
const showAssessmentDialog = (row: any) => {
  currentStudents.value = selectedRows.value;
  assessmentForm.value = {
    priority: "immediate",
    location: "",
    counselorId: null,
    appointmentTime: null
  };
  dialogVisible.value = true;
};

// 提交评估安排
const submitAssessment = () => {
  if (!assessmentFormRef.value) return;

  assessmentFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交逻辑
      let message = "";
      const selectedCounselor = counselors.value.find(c => c.id === assessmentForm.value.counselorId);
      const timeDisplay = assessmentForm.value.appointmentTime
          ? new Date(assessmentForm.value.appointmentTime).toLocaleString()
          : "未选择";

      const studentNames = currentStudents.value.map(student => student.studentName).join(',');

      if (assessmentForm.value.priority === "none") {
        message = `已为 ${studentNames} 标记为暂不用评估`;
      } else {
        message = `已为 ${studentNames} 安排评估\n` +
            `咨询师: ${selectedCounselor?.name || '未选择'}\n` +
            `时间: ${timeDisplay}\n` +
            `地点: ${assessmentForm.value.location}`;
      }

      ElMessageBox.confirm(
          message,
          "确认提交",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "question",
          }
      )
          .then(() => {
            ElMessage.success("评估安排提交成功");
            dialogVisible.value = false;
          })
          .catch(() => { });
    }
  });
};

// 处理弹窗关闭
const handleDialogClose = () => {
  // 清理弹窗数据
  currentStudents.value = [];
};

// 监听表格选中项变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

const activeTab = ref('pending');

onMounted(() => {
  getList('pending');
  getList('arranged');
});
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    h2 {
      margin: 0;
      font-size: 18px;
    }
    .stats {
      display: flex;
      gap: 20px;
      font-weight: bold;
    }
  }

  .search-form {
    display: flex;
    margin-left: 10px;
    margin-bottom: 10px;
    .el-input {
      width: 100%;
      max-width: 600px;
    }
  }

  .bottom-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30px;
    font-size: 14px;
    padding: 0 10px;
    color: #606266;

  }
}
/* 弹窗样式 */
.tips {
  margin-top: 10px;
}
</style>